/**
 * Created by 51ibm on 2017/4/26.
 */

import { Platform, Dimensions, Alert } from 'react-native';
import InitDB from '../database/init-db.js';

import Constant from '../constant/constant.js';

import { uuid } from './util.js';
import Util from './util'
import Alipay from 'react-native-yunpeng-alipay'

export default class Http {

    static timeout_fetch(fetch_promise, timeout = 55000) {
        let timeout_fn = null;
        // alert('timeout_fetch');

        //这是一个可以被reject的promise
        let timeout_promise = new Promise(function (resolve, reject) {
            timeout_fn = function () {
                reject('网络超时');
            };
        });

        //这里使用Promise.race，以最快 resolve 或 reject 的结果来传入后续绑定的回调
        let abortable_promise = Promise.race([
            fetch_promise,
            timeout_promise
        ]);

        setTimeout(function () {
            timeout_fn();
        }, timeout);

        return abortable_promise;
    }

    /**
     * @param {string} url 接口地址
     * @param {string} method 请求方法：GET、POST，只能大写
     * @param {JSON} [params=''] body的请求参数，默认为空
     * @return 返回Promise
     */
    static baseRequest(url, method, fc, params = {}) {

        const token = Util.getToken();

        let header = {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
        };
        let empId = Util.getEmpId();

        let date = new Date();
        let mobileClickTime = date.getDate();
        let mobileClickTimeDesc = date.Format('yyyy-MM-dd hh:mm:ss');

        let commonData = {
            os: Platform.OS,
            osVersion: Platform.Version,
            version: Constant.version,
            syncDate: InitDB.getBizDate(),
            mobileClickTime: mobileClickTimeDesc,
            mobileUploadTime: mobileClickTimeDesc,
            fc: fc,
            empId: empId,
            project: Constant.product,
        }
        let data = Object.assign(commonData, params)

        console.log('request url:', Constant.serverUrl + url, fc, empId, data);  //打印请求参数

        return new Promise(function (resolve, reject) {
            Http.timeout_fetch(fetch(Constant.serverUrl + url, {
                method: method,
                headers: header,
                body: JSON.stringify(data)   //body参数，通常需要转换成字符串后服务器才能解析
            }))
                .then((response) => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        console.warn(response);
                        return { ok: response.ok, status: response.status, statusText: response.statusText }
                    }
                })
                .then((responseData) => {
                    console.log('res:', url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch((err) => {
                    // alert('error:'+error);
                    console.log('err:', url, err);   //网络请求失败返回的数据
                    reject(err);
                });
        });
    }

    /**
     * POST方式请求数据
     * @param url
     * @param fc
     * @param empId
     * @param params
     * @returns {返回Promise}
     */
    static post(url, fc, params = {}) {
        return Http.baseRequest(url, 'POST', fc, params)
    }

    /**
     * GET方式请求数据
     * @param url
     * @param fc
     * @param empId
     * @param params
     * @returns {返回Promise}
     */
    static get(url, fc, params = '') {
        return Http.baseRequest(url, 'GET', fc, params)
    }

    /**
     * 通用请求API，根据urlInfo提供的信息，自动调用POST或GET请求
     * @param urlInfo
     * @param empId
     * @param params
     * @returns {返回Promise}
     */
    static fetch(urlInfo, params = '') {
        const url = urlInfo.url;
        const fc = urlInfo.fc;
        let method = 'POST';
        if (urlInfo.method) {
            method = urlInfo.method.toUpperCase();
        }
        if (method == 'POST') {
            return Http.post(url, fc, params);
        } else if (method == 'GET') {
            return Http.get(url, fc, params);
        }

    }

    static post_upload(fc, params = {}) {
        let url = '/mobile/post.do?action=save';
        return Http.post(url, fc, params);
    }


    static post_dataObj(obj, params = '') {
        let url = '/mobile/login.do?action=dataInfo';
        const empId = Util.getEmpId();


        let data = {
            objId: obj,
            empId: empId,
            ...params
        }
        return Http.post(url, 'dataObj', data);
    }


    /**上传附件，用FormData提交*/
    static post_image(fc, uri, imageIdex, photokey) {
        let url = '/mobile/post.do?action=saveImage';

        let date = new Date();
        let mobileClickTime = date.getDate();
        let mobileClickTimeDesc = date.Format('yyyy-MM-dd hh:mm:ss');

        let formData = new FormData();
        formData.append('fc', fc);
        formData.append('file', { uri: uri, type: ' multipart/form-data', name: uri });
        formData.append('syncDate', InitDB.getBizDate());
        formData.append('imageIndex', imageIdex);
        formData.append('photoKey', photokey);
        formData.append('mobileClickTime', mobileClickTimeDesc);
        formData.append('mobileUploadTime', mobileClickTimeDesc);

        let options = {};
        options.body = formData;
        options.method = 'post';

        return new Promise(function (resolve, reject) {

            Http.timeout_fetch(fetch(Constant.serverUrl + url, options).then((response) => response.json())
                .then((responseData) => {
                    console.log('res:', url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch((err) => {
                    console.log('err:', url, err);   //网络请求失败返回的数据
                    reject(err);
                }));
        });
    }

    /**上传realm文件*/
    static post_dbFile() {
        let url = Constant.serverUrl + '/mobile/post.do?action=saveDbFile';
        let path = InitDB.getRealmPath();
        // alert(url);
        //return;

        let date = new Date();
        let mobileClickTime = date.getDate();
        let mobileClickTimeDesc = date.Format('yyyy-MM-dd hh:mm:ss');


        ///	platform="android";
        if (Platform.OS === 'android') {
            path = "file://" + path;
        }

        //let type = "multipart/form-data";

        let formData = new FormData();
        formData.append('file', { uri: path, type: 'application/octet-stream', name: 'realm' });
        formData.append('syncDate', InitDB.getBizDate());
        if (InitDB.getCurrentUser()) {
            formData.append('empId', InitDB.getCurrentUser().empid);
        }
        formData.append('mobileClickTime', mobileClickTimeDesc);
        formData.append('mobileUploadTime', mobileClickTimeDesc);


        let options = {};
        options.body = formData;
        options.method = 'post';

        return new Promise(function (resolve, reject) {
            Http.timeout_fetch(fetch(url, options).then((response) => {
                // alert(response.json);
                return response.json()
            })
                .then((responseData) => {
                    console.log('res:', url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch((err) => {
                    console.log('err:', url, err);   //网络请求失败返回的数据
                    reject(err);
                }));
        });
    }

    static alipay(orderId, productName, price, success, fail) {

        let params = {
            orderId:orderId,
            productName: productName,
            price: price,
        }

        Http.post_upload('aliPreparePay', params)
            .then((data) => {


                    /*打开支付宝进行支付*/
                    Alipay.pay(data.returnType.other).then((data) => {
                      if (data.length && data[0].resultStatus) {
                        /*处理支付结果*/
                        switch (data[0].resultStatus) {
                           case "9000":
                             success && success(data)
                             break;
                           case "8000":
                             fail && fail('支付结果未知,请查询订单状态')
                             break;
                           case "4000":
                             fail && fail('订单支付失败')
                             break;
                           case "5000":
                             fail && fail('重复请求')
                             break;
                           case "6001":
                             fail && fail('用户中途取消')
                             break;
                           case "6002":
                             fail && fail('网络连接出错')
                             break;
                           case "6004":
                             fail && fail('支付结果未知,请查询订单状态')
                             break;
                           default:
                             fail && fail('其他失败原因')
                             break;
                         }
                       } else {
                         fail && fail('其他失败原因')
                       }
                     }, (err) => {
                       fail && fail('支付失败，请重新支付')
                     }
                   )
            })




    }


    static goumai() {
        let Platform = require('Platform');
        let platform = Platform.OS;
        ///	platform="android";
        if (platform != 'android') {
            alert('ios用户暂不能购买，需要去安卓手机进行购买！');
            return;
        }

        Alert.alert('温馨提醒', '确认要购买专栏吗（支付宝支付））？', [
            {
                text: '取消', onPress: () => {
                }
            },
            {
                text: '确定', onPress: () => {
                    Http.alipay(InitDB.getCurrentUser().empid, '语音音频', '199', Http.paySuccess, Http.payFail);
                }
            }
        ])
    }

    static paySuccess(msg) {
        alert('支付成功');
        InitDB.getRealm().write(() => {
            // Create a book object

            let date = new Date();
            let mobileClickTime = date.getDate();
            let mobileClickTimeDesc = date.Format('yyyy-MM-dd hh:mm:ss');

            realm.create('COURSE_USER', {
                ID_: InitDB.getCurrentUser().empId + "_" + mobileClickTimeDesc,
                empId: InitDB.getCurrentUser().empid,
                COURSE_ID: InitDB.getCourses()[0].ID_,
            });
        });
    }

    static payFail(err) {
        alert('支付失败' + err);
    }

}

module.exports = Http;
